package cn.com.company.main.client.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.com.company.main.client.control.AdvancedComboBox;
import cn.com.company.main.client.control.IcbomViewConfig;
import cn.com.company.main.client.entity.FileModel;
import cn.com.company.main.client.entity.IcbomchildItem;
import cn.com.company.main.client.entity.TItem;
import cn.com.company.main.client.entity.VwWebbomIcitem;
import cn.com.company.main.client.service.GreetingService;
import cn.com.company.main.client.service.GreetingServiceAsync;

import com.extjs.gxt.samples.resources.client.Resources;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseTreeLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.data.ModelKeyProvider;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.event.SelectionService;
import com.extjs.gxt.ui.client.event.SourceSelectionChangedListener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGrid;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGridCellRenderer;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

public class BomForwardQueryWindow extends Window {
	public static BomForwardQueryWindow instance;
	private Viewport viewport;
	private ContentPanel westPanel;
	private LayoutContainer container;
	private ContentPanel northPanel;
	private ContentPanel southPanel;

	private TreeStore<FileModel> store;
	private TreePanel<FileModel> tree;
	private TreeLoader<FileModel> loader;

	private Grid<VwWebbomIcitem> itemGrid;
	private ListStore<VwWebbomIcitem> itemGridstore;
	private ColumnModel cm;

	private TreeGrid<ModelData> treeGrid;
	private TreeStore<IcbomchildItem> treeGridStore;
	private TreeLoader<IcbomchildItem> treeGridLoader;
	private ColumnModel treeGridCm;

	private AdvancedComboBox combox;
	private ListStore<TItem> cBoxStore;
	private Button searchBtn;
	private Button exportBtn;
	private boolean isLarge = true;

	final GreetingServiceAsync service = GWT.create(GreetingService.class);

	public static BomForwardQueryWindow getInstance(String title,
			String iconStyleName) {
		if (instance == null) {
			instance = new BomForwardQueryWindow(title, iconStyleName);
		}
		return instance;
	}

	public BomForwardQueryWindow(String title, String iconStyleName) {
		setIcon(IconHelper.createStyle(iconStyleName));
		setMinimizable(true);
		setMaximizable(true);
		setHeading(title);
		setSize(900, 550);
		setLayout(new FitLayout());

		viewport = new Viewport();
		viewport.setLayout(new BorderLayout());
		createWestPanel();
		createContainer();
		buildTree();
		add(viewport);
	}

	@Override
	protected void onShow() {
		super.onShow();
		setSize(905, 555);
	}

	private void createWestPanel() {
		BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST, 250,
				150, 350);
		data.setMargins(new Margins(2, 0, 2, 2));

		westPanel = new ContentPanel();
		westPanel.setBodyBorder(true);
		westPanel.setLayout(new FitLayout());
		westPanel.setLayoutOnChange(true);
		westPanel.setScrollMode(Scroll.AUTO);

		combox = new AdvancedComboBox();
		westPanel.getHeader().addTool(combox);
		
		searchBtn = new Button("搜索");
		searchBtn.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				String key = combox.getInputValue();
				List<FileModel> list = tree.getStore().getAllItems();
				boolean flag = false;
				
				for (FileModel model: list) {
					if(model.getName().indexOf(key) != -1 ||  model.getId().indexOf(key) != -1){
						//TODO
						
						flag = true;
						break;
					}
				}
				if(!flag){
					Info.display("提示", "未搜索到相关的信息!");
				}
			}
		});
		westPanel.getHeader().addTool(searchBtn);
		viewport.add(westPanel, data);
	}

	public void createContainer() {
		BorderLayoutData data = new BorderLayoutData(LayoutRegion.CENTER);
		container = new LayoutContainer();
		container.setLayout(new BorderLayout());
		container.setLayoutOnChange(true);
		createNorthPanel();
		createSouthPanel();
		viewport.add(container, data);
	}

	public void createNorthPanel() {
		BorderLayoutData data = new BorderLayoutData(LayoutRegion.CENTER);
		data.setMargins(new Margins(2));
		northPanel = new ContentPanel();
		northPanel.setBodyBorder(true);
		northPanel.setHeaderVisible(false);
		northPanel.setLayout(new FitLayout());
		northPanel.setLayoutOnChange(true);
		northPanel.add(buildItemGrid());
		container.add(northPanel, data);
	}

	public void createSouthPanel() {
		BorderLayoutData data = new BorderLayoutData(LayoutRegion.SOUTH, 400,
				200, 1000);
		data.setSplit(true);
		data.setMargins(new Margins(2));
		southPanel = new ContentPanel();
		southPanel.setBodyBorder(true);
		southPanel.setLayout(new FitLayout());
		southPanel.setLayoutOnChange(true);
		southPanel.setScrollMode(Scroll.AUTO);

		exportBtn = new Button("导出");
		southPanel.getHeader().addTool(exportBtn);
		initTreeGrid();
		container.add(southPanel, data);
	}

	public void buildTree() {
		RpcProxy<List<FileModel>> proxy = new RpcProxy<List<FileModel>>() {
			@Override
			protected void load(Object loadConfig,
					AsyncCallback<List<FileModel>> callback) {
				service.getIcbomModel((FileModel) loadConfig, callback);
			}
		};

		loader = new BaseTreeLoader<FileModel>(proxy) {
			@Override
			public boolean hasChildren(FileModel parent) {
				return parent instanceof FileModel;
			}
		};

		store = new TreeStore<FileModel>(loader);
		store.setKeyProvider(new ModelKeyProvider<FileModel>() {
			public String getKey(FileModel model) {
				return model.<String> get("id");
			}
		});

		tree = new TreePanel<FileModel>(store);
		// tree.setStateful(true);
		tree.setDisplayProperty("name");
		tree.setId("tree_");
		tree.getStyle().setLeafIcon(Resources.ICONS.text());
		tree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
		//tree.setAutoLoad(true);
		
		SelectionService.get().addListener(new SourceSelectionChangedListener(tree.getSelectionModel()));
	    SelectionService.get().register(tree.getSelectionModel());
	    
		tree.setIconProvider(new ModelIconProvider<FileModel>() {

			public AbstractImagePrototype getIcon(FileModel model) {
				if (!(model instanceof FileModel)) {
					String ext = model.getType();

					if ("icbom".equals(ext)) {
						return Resources.ICONS.text();
					} else if ("java".equals(ext)) {
						return IconHelper
								.createPath("samples/images/icons/page_white_cup.png");
					} else if ("html".equals(ext)) {
						return IconHelper
								.createPath("samples/images/icons/html.png");
					} else {
						return IconHelper
								.createPath("samples/images/icons/page_white.png");
					}
				}
				return null;
			}
		});
		tree.addListener(Events.OnClick,
				new Listener<TreePanelEvent<FileModel>>() {
					@Override
					public void handleEvent(TreePanelEvent<FileModel> be) {
						FileModel model = be.getItem();
						if (model == null) {
							return;
						}
						if (model.getItemId() != null) {
							service.getIcItemByItemId(model.getItemId(),
									new AsyncCallback<List<VwWebbomIcitem>>() {

										@Override
										public void onSuccess(
												List<VwWebbomIcitem> list) {
											itemGridstore.removeAll();
											itemGridstore.add(list);
											if (list == null
													|| list.size() == 0) {
												initTreeGrid();// 初始化TreeGrid
												if (isLarge) {
													southPanel.setSize(
															southPanel
																	.getWidth() + 1,
															southPanel
																	.getHeight() + 1);
												} else {
													southPanel.setSize(
															southPanel
																	.getWidth() - 1,
															southPanel
																	.getHeight() - 1);
												}
											}
										}

										@Override
										public void onFailure(Throwable caught) {
											MessageBox.alert("错误", caught
													.getLocalizedMessage(),
													null);
										}
									});
						}
					}
				});

		westPanel.add(tree);
		tree.expandAll();
	}

	public Grid<VwWebbomIcitem> buildItemGrid() {
		DateTimeFormat dateFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		ColumnConfig column = new ColumnConfig();

		column.setId("finterId");
		column.setHeader("InterID");
		column.setWidth(100);
		column.setHidden(true);
		column.setRowHeader(true);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fitemId");
		column.setHeader("ItemID");
		column.setWidth(100);
		column.setHidden(true);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fBomNumber");
		column.setHeader("BOM单编号");
		column.setWidth(100);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fnumber");
		column.setHeader("物料代码");
		column.setWidth(100);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fname");
		column.setHeader("物料名称");
		column.setWidth(400);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fqty");
		column.setHeader("数量");
		column.setWidth(50);
		column.setNumberFormat(NumberFormat.getFormat("0"));
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fyield");
		column.setHeader("成品率（%）");
		column.setWidth(80);
		column.setNumberFormat(NumberFormat.getFormat("0"));
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fuseStatus");
		column.setHeader("状态");
		column.setWidth(50);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fstatus");
		column.setHeader("审核");
		column.setWidth(50);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fversion");
		column.setHeader("版本");
		column.setWidth(50);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fcheckDate");
		column.setHeader("建立日期");
		column.setWidth(70);
		column.setDateTimeFormat(dateFormat);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fenterTime");
		column.setHeader("最后更新日期");
		column.setWidth(85);
		column.setDateTimeFormat(dateFormat);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("fuseDate");
		column.setHeader("使用日期");
		column.setWidth(70);
		column.setDateTimeFormat(dateFormat);
		configs.add(column);

		cm = new ColumnModel(configs);

		itemGridstore = new ListStore<VwWebbomIcitem>();
		List<VwWebbomIcitem> list = new ArrayList<VwWebbomIcitem>();
		itemGridstore.add(list);

		itemGrid = new Grid<VwWebbomIcitem>(itemGridstore, cm);
		itemGrid.setBorders(false);
		itemGrid.setStripeRows(true);
		itemGrid.setColumnLines(true);
		itemGrid.setColumnReordering(true);
		itemGrid.getView().setViewConfig(new IcbomViewConfig());

		itemGrid.addListener(Events.RowClick,
				new Listener<GridEvent<ModelData>>() {

					@Override
					public void handleEvent(GridEvent<ModelData> be) {
						VwWebbomIcitem item = (VwWebbomIcitem) be.getModel();
						final String interId = item.getFinterId() + "";
						initTreeGridLoader(interId);
						treeGridStore = new TreeStore<IcbomchildItem>(
								treeGridLoader);
						treeGrid = new TreeGrid<ModelData>(treeGridStore,
								treeGridCm);
						treeGrid.setAutoLoad(true); //TODO
						treeGrid.expandAll();
						treeGrid.getStyle().setLeafIcon(Resources.ICONS.text());
						southPanel.removeAll();
						southPanel.add(treeGrid);
					}
				});
		return itemGrid;
	}

	public void initTreeGrid() {
		treeGridStore = new TreeStore<IcbomchildItem>();
		createColumnConfig();
		treeGrid = new TreeGrid<ModelData>(treeGridStore, treeGridCm);
		treeGrid.setBorders(false);
		treeGrid.getStyle().setLeafIcon(IconHelper.createStyle("icon-page"));
		treeGrid.setAutoExpandColumn("fitemid");
		treeGrid.setWidth("100%");
		treeGrid.setHeight("100%");
		treeGrid.getStyle().setLeafIcon(Resources.ICONS.text());
		southPanel.removeAll();
		southPanel.add(treeGrid);
	}

	public void initTreeGridLoader(final String interId) {
		RpcProxy<List<IcbomchildItem>> proxy = new RpcProxy<List<IcbomchildItem>>() {
			@Override
			protected void load(Object loadConfig,
					AsyncCallback<List<IcbomchildItem>> callback) {
				service.getIcbomItem((IcbomchildItem) loadConfig, interId,
						callback);
			}
		};
		treeGridLoader = new BaseTreeLoader<IcbomchildItem>(proxy) {
			@Override
			public boolean hasChildren(IcbomchildItem parent) {
				return parent instanceof IcbomchildItem;
			}
		};
	}

	private ColumnModel createColumnConfig() {
		ColumnConfig fnumber = new ColumnConfig("fnumber", "物料代码", 200);
		fnumber.setRenderer(new TreeGridCellRenderer<ModelData>());

		ColumnConfig fname = new ColumnConfig("fname", "物料名称", 350);

		ColumnConfig fqty = new ColumnConfig("fqty", "用量", 100);
		fqty.setNumberFormat(NumberFormat.getFormat("0"));

		ColumnConfig fscrap = new ColumnConfig("fscrap", "损耗率（%）", 100);
		fscrap.setNumberFormat(NumberFormat.getFormat("0"));

		ColumnConfig fitemid = new ColumnConfig("fitemid", "fitemid", 50);
		fitemid.setHidden(true);

		ColumnConfig fparentid = new ColumnConfig("fparentid", "fparentid", 50);
		fparentid.setHidden(true);

		ColumnConfig finterid = new ColumnConfig("finterid", "finterid", 50);
		finterid.setHidden(true);

		treeGridCm = new ColumnModel(Arrays.asList(fnumber, fname, fqty,
				fscrap, fitemid, fparentid, finterid));
		return treeGridCm;
	}

	private native String getTemplate() /*-{
		return [
				'<tpl for=".">',
				'<div class="x-combo-list-item" qtip="{slogan}" qtitle="State Slogan">{name}</div>',
				'</tpl>' ].join("");
	}-*/;

}
